package com.hexinfo.dmpro.monitor.service;


import cn.hutool.core.util.StrUtil;
import com.hexinfo.dmpro.common.base.BaseService;
import com.hexinfo.dmpro.common.base.Page;
import com.hexinfo.dmpro.common.base.PageResult;
import com.hexinfo.dmpro.monitor.dao.*;
import com.hexinfo.dmpro.monitor.model.base.MonitorBaseModel;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import com.hexinfo.dmpro.monitor.model.MonitorTaskModel;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import com.hexinfo.dmpro.monitor.model.cm.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Auther:ht.zhou
 * @Date:2024/01/04/16:29
 * @Description:
 */
@Service
public class MonitorSummaryService extends BaseService {

    @Autowired
    private ClusterHostRoleService clusterHostRoleService;
    @Autowired
    private ClusteAllRolesService clusteAllRolesService;
    @Autowired
    private CmStateDao cmStateDao;
    @Autowired
    private CmYarnPoolDao cmYarnPoolDao;
    @Autowired
    private CmImpalaPoolDao cmImpalaPoolDao;
    @Autowired
    private MonitorDao monitorDao;
    @Autowired
    private ClusterWhDao clusterWhDao;


    /**
     * 信息总览 服务状态数据测试
     *
     * @return
     */
    public List<ServiceCountInfo> queryOverviewServiceRealTime(StateBaseReqModel model) {
        List<ServiceCountInfo> serviceCountInfos = cmStateDao.queryServiceRealTime(model);
        Map<String, ServiceCountInfo> map = new HashMap<>();
        if (serviceCountInfos != null && serviceCountInfos.size() > 0) {
            serviceCountInfos.forEach(item -> {
                map.put(item.getType(), item);
            });
        }

        //把不符合条件的type的填0补充
        List<ServiceCountInfo> allServiceList = cmStateDao.queryServiceNullCount(model);
        if (allServiceList != null && allServiceList.size() > 0) {
            allServiceList.forEach(allItem -> {
                String type = allItem.getType();
                String name = allItem.getName();
                if (map.get(type) == null) {
                    ServiceCountInfo serviceCountInfo = new ServiceCountInfo();
                    serviceCountInfo.setType(type);
                    serviceCountInfo.setName(name);
                    serviceCountInfo.setBad(0);
                    serviceCountInfo.setConc(0);
                    serviceCountInfo.setGood(0);
                    serviceCountInfos.add(serviceCountInfo);
                }
            });
        }
        return serviceCountInfos;
    }

    public List<ServiceStateCount> queryAllServiceCount(){
        return cmStateDao.queryAllServiceCount();
    }

    public PageResult queryAllService(Page page, MonitorReq req){
        return selectPage(cmStateDao, "queryAllService", page, req) ;

    }

    /**
     *查询集群监控信息总览 yarn资源的cpu使用率和内存使用率
     */
    public List<UtilizationResourceInfo> selYarnUtilization(ResourceBaseReqModel req){
        return cmYarnPoolDao.selYarnPoolUtilization(req);
    }

    /**
     * 查询集群监控信息总览 impala资源的内存使用率
     */
    public List<UtilizationImpalaInfo> selImpalaPoolUtilization(ResourceBaseReqModel req){
        return cmImpalaPoolDao.selImpalaPoolUtilization(req);
    }

    /**
     * 查询集群监控信息总览 所有资源使用率
     * @param req
     * @return
     */
    public List<Object> selAllUtilization(ResourceBaseReqModel req) {
        List<Object> allUtilizationData = new ArrayList<>();

        //selYarnUtilization
        List<UtilizationResourceInfo> yarnUtilization = selYarnUtilization(req);
        allUtilizationData.addAll(yarnUtilization);

        //selImpalaPoolUtilization
        List<UtilizationImpalaInfo> impalaUtilization = selImpalaPoolUtilization(req);
        allUtilizationData.addAll(impalaUtilization);

        return allUtilizationData;
    }

    /**
     * 查询集群监控信息总览 任务数
     */
    public Map<String, Object> getCombinedTaskCount(MonitorReq Req) {
        Map<String, Object> result = new HashMap<>();

        // 创建 YARN 和 IMPALA 的请求参数
        MonitorReq yarnReq = new MonitorReq();
        MonitorReq impalaReq = new MonitorReq();

        // 设置共同的参数
        yarnReq.setCenterId(Req.getCenterId());
        yarnReq.setCmFlag(Req.getCmFlag());
        yarnReq.setClusterFlag(Req.getClusterFlag());

        impalaReq.setCenterId(Req.getCenterId());
        impalaReq.setCmFlag(Req.getCmFlag());
        impalaReq.setClusterFlag(Req.getClusterFlag());

        // 设置特定的监控类型
        yarnReq.setMonitorType("YARN");
        impalaReq.setMonitorType("IMPALA");

        // 获取数据
        Map<String, Object> yarnData = monitorDao.selTaskCount(yarnReq);
        Map<String, Object> impalaData = monitorDao.selTaskCount(impalaReq);

        // 检查数据是否为null，如果是则设置默认值
        result.put("YARN", yarnData != null ? yarnData : createDefaultDataMap());
        result.put("IMPALA", impalaData != null ? impalaData : createDefaultDataMap());

        return result;
    }

    private Map<String, Object> createDefaultDataMap() {
        Map<String, Object> defaultData = new HashMap<>();
        defaultData.put("toDayRunning", 0);
        defaultData.put("toDaySubmit", 0);
        defaultData.put("toDayFailed", 0);
        defaultData.put("toDaySucceeded", 0);
        return defaultData;
    }

    public Object monitorStatusInquiry() {
        Map<String, Object> selectPage = monitorDao.selectPage();
        selectPage.put("CMNUM",clusterWhDao.cmNum());
        return selectPage;
    }

    public PageResult cmPageMessage(Page page, CmMessage cmMessage){
        return selectPage(monitorDao, "selectPageCm", page,cmMessage);
    }

    public PageResult selectAllHost(Page page,MonitorReq model){
        return selectPage(cmStateDao, "selectAllHost", page, model);
    }

    public PageResult queryRoleStatePage(StateBaseReqModel model,Page page){
        return selectPage(cmStateDao, "queryRoleStateNow", page, model);
    }

    //cpu使用率
    public List<DistributionDto> cpuUsed(String cmFlag , String clusterFlag , String startTime
            , String endTime){
        Long num = cmStateDao.cpuNum(cmFlag, clusterFlag);
        return cmStateDao.cpuUsed(cmFlag,clusterFlag,startTime,endTime,num);
    }

    //cpu分配率
    public List<DistributionDto> cpuDistribution(String cmFlag , String clusterFlag , String startTime
            , String endTime){
        Long num = cmStateDao.cpuNum(cmFlag, clusterFlag);
        return cmStateDao.cpuDistribution(cmFlag,clusterFlag,startTime,endTime,num);
    }

    //内存使用率
    public List<DistributionDto> memoryUsed(String cmFlag , String clusterFlag , String startTime
            , String endTime){
        Long num = cmStateDao.memoryNum(cmFlag, clusterFlag);
        return cmStateDao.memoryUsed(cmFlag,clusterFlag,startTime,endTime,num);
    }

    //内存分配率
    public List<DistributionDto> memoryDistribution(String cmFlag , String clusterFlag , String startTime
            , String endTime){
        Long num = cmStateDao.memoryNum(cmFlag, clusterFlag);
        return cmStateDao.memoryDistribution(cmFlag,clusterFlag,startTime,endTime,num);
    }

    //hdfs使用率
    public List<DistributionDto> hdfsUsed(String cmFlag , String clusterFlag , String startTime
            , String endTime){
        return cmStateDao.hdfsUsed(cmFlag,clusterFlag,startTime,endTime);
    }

    //所有集群基础信息
    public List<CmResourceData> cmResourceBasicData(){
        List<CmResourceData> cmResourceDatas = clusterWhDao.cmBasicData();
        for (CmResourceData cmResourceData : cmResourceDatas) {
            //服务状态
            List<ServiceState> serviceStates = cmStateDao.queryServiceStateNow(cmResourceData.getCmFlag(), cmResourceData.getClusterFlag());
            //hdfs使用情况
            String hdfsUse = cmStateDao.queryHdfsUse(cmResourceData.getCmFlag(), cmResourceData.getClusterFlag());
            //yarn的root队列
            DetailResourceInfo rootPool = cmYarnPoolDao.getRootPool(cmResourceData.getCmFlag(), cmResourceData.getClusterFlag());
            //集群信息中的impala内存分配值
            String cmImpalaMax = clusterWhDao.cmImpalaMax(cmResourceData.getCmFlag(), cmResourceData.getClusterFlag());
            //集群所有impala资源池使用情况汇总
            String cmImpalaUse = cmImpalaPoolDao.cmImpalaUse(cmResourceData.getCmFlag(), cmResourceData.getClusterFlag());

            BigDecimal cpuUse = new BigDecimal(rootPool.getUsedCores());
            BigDecimal cpuMax = new BigDecimal(rootPool.getMaxCores());
            BigDecimal gbUse = new BigDecimal(rootPool.getUsedGB());
            BigDecimal gbMax = new BigDecimal(rootPool.getMaxGB());
            String cpu = cpuUse.divide(cpuMax, 2, BigDecimal.ROUND_HALF_UP).toString();
            String gb = gbUse.divide(gbMax, 2, BigDecimal.ROUND_HALF_UP).toString();
            double cpuDou = Double.parseDouble(cpu)*100;
            double gbDou = Double.parseDouble(gb)*100;
            DecimalFormat df = new DecimalFormat("#");

            cmResourceData.setServiceStates(serviceStates);
            cmResourceData.setHdfsUse(hdfsUse);
            cmResourceData.setYarnCpuUsePro(df.format(cpuDou));
            cmResourceData.setYarnMemoryUsePro(df.format(gbDou));
            //判断集群是否有impala服务
            if(StrUtil.isBlank(cmImpalaMax) || StrUtil.isBlank(cmImpalaUse)){
                cmResourceData.setImpalaMemoryUsePro("0");
            }else {
                double l = Double.parseDouble(cmImpalaMax)*1024*1024*1024;
                BigDecimal impalaMax = new BigDecimal(Double.toString(l));
                BigDecimal impalaUse = new BigDecimal(cmImpalaUse);
                String impalaGb = impalaUse.divide(impalaMax, 2, BigDecimal.ROUND_HALF_UP).toString();
                double impalaGbDou = Double.parseDouble(impalaGb)*100;
                cmResourceData.setImpalaMemoryUsePro(df.format(impalaGbDou));
            }
        }
        return cmResourceDatas;
    }
}
